//jQuery扩展方法
(function ($) {

    if (!!jQuery.validator) {
        // 联系电话(手机/电话皆可)验证
        jQuery.validator.addMethod("isTel", function (value, element) {
            let length = value.length;
            let mobile = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
            let tel = /^(\d{3,4}-?)?\d{7,9}$/g;
            return this.optional(element) || tel.test(value) || (length == 11 && mobile.test(value));
        }, "请正确填写您的联系方式");
    }

    $.fn.extend({
        //遍历select 增加option
        addOptionsWithKeyValue: function (keyValuePairs) {
            for (let key in keyValuePairs) {
                $(this).append(
                    '<option value="' + keyValuePairs[key].id + '">' + keyValuePairs[key].name + '</option>'
                );
            }
        },
        //序列化函数
        serializeObject: function () {
            let o = {};
            let a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value.trim() || '');
                } else {
                    o[this.name] = this.value.trim() || '';
                }
            });
            return o;
        },
        hwTreeGrid: function (obj) {
            let $this = $(this);
            if (!typeof obj === 'object') {
                throw new Error('data must be array')
            }
            $this.html('');
            if (obj.length === 0) {
                return;
            }
            let html = obj.map(x => {
                let checked = '';
                if (x.display) {
                    checked = 'checked'
                }
                return '<tr data-id="' + x.id + '" data-parent="' + x.parentId + '" data-level="' + x.level + '">'
                    + '<td data-column="name">' + x.name + '</td>'
                    + '<td><input class="treeGrid" value="' + x.id + '" type="checkbox" ' + checked + ' /></td></tr>';
            });
            $this.html(html.join(''));
            $this.find('tr').each(function (index, row) {
                let $row = $(row),
                    level = $row.data('level'),
                    id = $row.data('id'),
                    $columnName = $row.find('td[data-column="name"]'),
                    children = $this.find('tr[data-parent="' + id + '"]');
                if (children.length) {
                    let expander = $columnName.prepend('' + '<i class="treegrid-expander fa fa-arrow-circle-right"></i>' + '');
                    children.hide();
                    expander.unbind('click').on('click', function (e) {
                        let $target = $(e.target);
                        if ($target.hasClass('treegrid-expander')) {
                            if ($target.hasClass('fa-arrow-circle-right')) {
                                $target.removeClass('fa-arrow-circle-right').addClass('fa-arrow-circle-down');
                                children.show(500);
                            } else {
                                $target.removeClass('fa-arrow-circle-down').addClass('fa-arrow-circle-right');
                                reverseHide($this, $row);
                            }
                        }
                    });
                }
                $columnName.prepend('' + '<i class="treegrid-indent" style="width:' + 30 * level + 'px"></i>' + '');
            });

            function reverseHide(table, element) {
                let $element = $(element),
                    id = $element.data('id'),
                    children = table.find('tr[data-parent="' + id + '"]');

                if (children.length) {
                    children.each(function (i, e) {
                        reverseHide(table, e);
                    });
                    $element.find('.fa-arrow-circle-down')
                        .removeClass('fa-arrow-circle-down')
                        .addClass('fa-arrow-circle-right');
                    children.hide();
                }
            }
        },
        hwTreeSelect: function (obj) {
            let $this = $(this);
            let html = [];
            for (let i in obj) {
                let parent = '';
                if (!!obj[i].parentId) {
                    parent = 'data-parent="' + obj[i].parentId + '"'
                }
                html.push('<option value="' + obj[i].id + '" ' + parent + '>' + obj[i].name + '</option>');
            }
            $this.append(html.join(''));
            $this.treeselect()
        },
        countToWithRow: function (arr) {
            if (arr.length <= 0) {
                throw new Error("data must be an arr")
            }
            let $this = $(this);
            let length = arr.length;
            let flexClass = 'col-xs-' + Math.floor(12 / length) + ' text-center';
            let html = [];
            for (let obj in arr) {
                html.push('<div class="' + flexClass + '">');
                html.push('<div class="hon-count">');
                html.push('<p class="hon-count-text-margin">' + arr[obj].name + '</p>');
                html.push('<p class="hon-count-text" data-from="0" data-speed="800" data-to="' + arr[obj].value + '"></p>');
                html.push('</div></div>')
            }
            $this.append(html.join(''));
            $('.hon-count-text').countTo()
        },
        honDataTable: function (obj) {
            let $this = $(this);
            let result = {
                'language': {
                    "processing": "处理中...",
                    "lengthMenu": "_MENU_ 记录/页",
                    "zeroRecords": "没有匹配的记录",
                    "info": "第 _START_ 至 _END_ 项记录，共 _TOTAL_ 项",
                    "infoEmpty": "第 0 至 0 项记录，共 0 项",
                    "infoFiltered": "(由 _MAX_ 项记录过滤)",
                    "infoPostFix": "",
                    "search": "搜索:",
                    "url": "",
                    "decimal": ",",
                    "thousands": ".",
                    "emptyTable": "未找到符合条件的数据",
                    "paginate": {
                        "first": "首页",
                        "previous": "上页",
                        "next": "下页",
                        "last": "末页"
                    }
                },
                "columns": obj.columns,
                'paging': obj.paging,
                "processing": true,
                'lengthChange': false,
                'searching': false,
                'ordering': true,
                'info': true,
                'autoWidth': false,
                'serverSide': true,
                'deferRender': true,
                'ajax': obj.httpRequest
            };
            if (!!obj.columnDefs) {
                result['columnDefs'] = obj.columnDefs
            }
            $this.DataTable(result);
        }
    })
})(jQuery);

var G = {
    chart: {
        showLoading: function (elementId) {
            let element = document.getElementById(elementId);
            let chart = echarts.init(element);
            chart.showLoading({
                text: "图表数据正在努力加载..."
            });
        },
        hideLoading: function (elementId) {
            let element = document.getElementById(elementId);
            let chart = echarts.init(element);
            chart.hideLoading()
        },
        showChart: function (elementId, option) {
            let element = document.getElementById(elementId);
            let chart = echarts.init(element);
            ElementQueries.listen();
            ElementQueries.init();
            new ResizeSensor(element, function () {
                chart.resize();
            });
            chart.setOption(option, true);
            chart.hideLoading();
        },
        initPieOption: function (obj, unit) {
            if (!unit) {
                unit = ''
            }
            return {
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}" + unit + " ({d}%)"
                },
                legend: {
                    orient: 'horizontal',
                    top: 'top',
                    data: obj.datas.map(x => x.name)
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: {
                            show: true
                        },
                        magicType: {
                            show: true,
                            type: ['pie']
                        },
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                series: [{
                    name: obj.seriesName,
                    type: 'pie',
                    radius: '75%',
                    center: ['50%', '55%'],
                    data: obj.datas,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        },
                        normal: {
                            label: {
                                show: false,
                                formatter: '{c}'
                            },
                            labelLine: {
                                show: false
                            }
                        }
                    }
                }]
            };
        },
        initLineAndBarOption: function (obj) {
            return {
                tooltip: {
                    trigger: 'axis'
                    // axisPointer: _axisPointer
                },
                toolbox: {
                    feature: {
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                legend: {
                    data: !!obj.datas ? obj.datas.map(x => x.name) : []
                },
                grid: {
                    left: '10',
                    right: '20',
                    bottom: '10',
                    containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    data: obj.xData,
                    axisTick: { // 轴标记
                        alignWithLabel: true
                    },
                    axisLabel: {
                        formatter: '{value} '
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} '
                    }
                }],
                series: obj.datas.map(x => {
                    let temp = x.name.indexOf('预算') !== -1 ? 'line' : 'bar'
                    x.type = temp;
                    x.data = x.datas.map(y => y.value);
                    return x;
                })
            };
        },
        initSingleBarOption: function (obj, unit) {
            if (!unit) {
                unit = ''
            }
            return {
                tooltip: {
                    trigger: 'axis'
                    // axisPointer: _axisPointer
                },
                toolbox: {
                    feature: {
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                legend: {
                    data: obj.legend
                },
                grid: {
                    left: '10',
                    right: '20',
                    bottom: '10',
                    containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    data: obj.xData,
                    axisTick: { // 轴标记
                        alignWithLabel: true
                    },
                    axisLabel: {
                        formatter: '{value} '
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} ' + unit
                    }
                }],
                series: [
                    {
                        name: obj.legend,
                        type: 'bar',
                        barWidth: '30%',
                        data: obj.data
                    }
                ]
            };
        },
        initBarOption: function (obj, stackable, unit) {
            if (!unit) {
                unit = ''
            }
            return {
                tooltip: {
                    trigger: 'axis'
                    // axisPointer: _axisPointer
                },
                toolbox: {
                    feature: {
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                legend: {
                    data: !!obj.datas ? obj.datas.map(x => x.name) : []
                },
                grid: {
                    left: '10',
                    right: '20',
                    bottom: '10',
                    containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    data: obj.xData,
                    axisTick: { // 轴标记
                        alignWithLabel: true
                    },
                    axisLabel: {
                        formatter: '{value} '
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} ' + unit
                    }
                }],
                series: !!obj.datas ? obj.datas.map(x => {
                    x.type = 'bar';
                    if (stackable) {
                        x.stack = '0'
                    }
                    x.barWidth = 30;
                    x.data = x.datas.map(y => y.value);
                    return x;
                }) : []
            };
        },
        initLineOption: function (obj, unit, showLabel) {
            if (!unit) {
                unit = ''
            }
            return {
                tooltip: {
                    trigger: 'axis'
                    // axisPointer: _axisPointer
                },
                legend: {
                    data: !!obj.datas ? obj.datas.map(x => x.name) : []
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: {
                            show: true
                        },
                        magicType: {
                            show: true,
                            type: []
                        },
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                calculable: true,
                xAxis: [{
                    type: 'category',
                    data: obj.xData
                }],
                yAxis: [{
                    axisTick: { // 轴标记
                        show: false,
                        length: 10,
                        lineStyle: {
                            color: 'green',
                            type: 'solid',
                            width: 2
                        }
                    },
                    axisLabel: {
                        show: true,
                        interval: 'auto', // {number}
                        formatter: '{value} ' + unit // Template formatter!
                    },
                    type: 'value'
                }],
                dataZoom: [{
                    show: showLabel,
                    realtime: true,
                    start: 0,
                    end: 100,
                    xAxisIndex: [0]
                }],
                series: !!obj.datas ? obj.datas.map(x => {
                    let temp = {}
                    temp.name = x.name
                    temp.type = 'line';
                    temp.data = x.datas.map(y => y.value);
                    temp.smooth = true;
                    return temp;
                }) : []
            };
        }
    },
    date: {
        rangePicker: function (elementId, obj) {
            let tempObj = {
                "showDropdowns": true,
                "linkedCalendars": false,
                "autoUpdateInput": true,
                "showCustomRangeLabel": false,
                "opens": "center",
                "maxDate": moment().format('MM/DD/YYYY'),
                "locale": {
                    "format": "MM/DD/YYYY",
                    "separator": " - ",
                    "applyLabel": "确认",
                    "cancelLabel": "取消",
                    "fromLabel": "开始",
                    "toLabel": "结束",
                    "customRangeLabel": "自定义",
                    "weekLabel": "周",
                    "daysOfWeek": [
                        "日",
                        "一",
                        "二",
                        "三",
                        "四",
                        "五",
                        "六"
                    ],
                    "monthNames": [
                        "一月",
                        "二月",
                        "三月",
                        "四月",
                        "五月",
                        "六月",
                        "七月",
                        "八月",
                        "九月",
                        "十月",
                        "十一月",
                        "十二月"
                    ],
                    "firstDay": 1
                }
            };
            $('#' + elementId).daterangepicker($.extend(tempObj, obj));
        },
        freshShowTime: function (element) {
            let headerTime = {

                prefix0: function (v) {
                    if (v >= 0 && v <= 9) {
                        v = "0" + v;
                    }
                    return v;
                },

                getFormatWeek: function (day) {
                    let week;
                    switch (day) {
                        case 1:
                            week = "星期一";
                            break;
                        case 2:
                            week = "星期二";
                            break;
                        case 3:
                            week = "星期三";
                            break;
                        case 4:
                            week = "星期四";
                            break;
                        case 5:
                            week = "星期五";
                            break;
                        case 6:
                            week = "星期六";
                            break;
                        default:
                            week = "星期日";
                    }
                    return week;
                },

                showHeaderFormatDate: function (element) {
                    let _this = this;
                    let _date = new Date();
                    let year = _date.getFullYear();
                    let month = _date.getMonth() + 1;
                    let day = _date.getDate();
                    let weekDay = _date.getDay();
                    let hour = _date.getHours();
                    let minute = _date.getMinutes();
                    let sec = _date.getSeconds();

                    let seperator1 = '.';
                    let seperator2 = ':';

                    let currentdate = year + seperator1 + _this.prefix0(month) + seperator1 + _this.prefix0(day) +
                        " " + _this.getFormatWeek(weekDay) + " " + _this.prefix0(hour) + seperator2 + _this.prefix0(minute) + seperator2 + _this.prefix0(sec);

                    $(element).text(currentdate);
                }
            };

            window.setInterval(function () {
                headerTime.showHeaderFormatDate(element)
            }, 1000);
        }
    },
    multiselect: {
        select: function (elementId) {
            let locales = {
                nonSelectedText: '未选择',
                selectAllText: '全部选中',
                allSelectedText: '全部选中',
                nSelectedText: '个项目已选中'
            }

            $(elementId).multiselect('destroy').multiselect($.extend({
                buttonWidth: '100%',
                includeSelectAllOption: true
            }, locales));
        }
    }
}
